<template>
  <div class="question-display">
    <div v-if="questions.length > 0" class="questions-container">
      <div class="question-navigation">
        <button class="nav-btn" @click="prevQuestion" :disabled="currentIndex === 0">
          上一题
        </button>
        <span class="question-progress">{{ currentIndex + 1 }} / {{ questions.length }}</span>
        <button class="nav-btn" @click="nextQuestion" :disabled="currentIndex === questions.length - 1">
          下一题
        </button>
        <div class="answer-card-wrapper">
          <button class="nav-btn" @click="toggleAnswerCard">
            答题卡
          </button>
          <div class="answer-card-panel" v-if="showAnswerCard">
            <div class="answer-card-title">答题进度</div>
            <div class="answer-card-grid">
              <div
                v-for="(q, index) in questions"
                :key="q.id"
                class="answer-card-item"
                :class="{
                  'answered': selectedAnswers[q.id],
                  'current': currentIndex === index
                }"
                @click="goToQuestion(index)"
              >
                {{ index + 1 }}
              </div>
            </div>
          </div>
        </div>
        <button class="submit-all-btn" @click="submitAllAnswers" v-if="!showAnswers">
          提交所有答案
        </button>
      </div>

      <div class="question-card">
        <div class="question-header">
          <span class="question-number">题目 {{ currentIndex + 1 }}</span>
          <span class="difficulty" :class="'level-' + currentQuestion.difficultyLevel">
            难度: {{ getDifficultyText(currentQuestion.difficultyLevel) }}
          </span>
        </div>
        
        <div class="question-content">
          {{ currentQuestion.questionContent }}
        </div>
        
        <div class="options">
          <div 
            v-for="option in ['A', 'B', 'C', 'D']" 
            :key="option"
            class="option"
            :class="{
              'selected': selectedAnswers[currentQuestion.id] === option,
              'correct': showAnswers && option === currentQuestion.correctAnswer,
              'wrong': showAnswers && selectedAnswers[currentQuestion.id] === option && option !== currentQuestion.correctAnswer
            }"
            @click="selectAnswer(currentQuestion.id, option)"
          >
            <span class="option-label">{{ option }}.</span>
            <span class="option-content">{{ currentQuestion['option' + option] }}</span>
          </div>
        </div>

        <div v-if="showAnswers" class="explanation">
          <div class="explanation-title">答案解析：</div>
          <div class="explanation-content">{{ currentQuestion.explanation }}</div>
        </div>
      </div>
    </div>
    
    <div v-else class="empty-state">
      <p>暂无题目，请先生成题目</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { generateQuestion, submitAnswers } from '@/api/question';

// 扩展的模拟数据
const questions = ref([]);

onMounted(async () => {
  // 监听 localStorage 变化
  window.addEventListener('storage', handleStorageChange);
  
  // 初始化加载题目
  await loadQuestions();
});

// 将 onUnmounted 移到这里
onUnmounted(() => {
  window.removeEventListener('storage', handleStorageChange);
});

// 处理 localStorage 变化
const handleStorageChange = async (e) => {
  if (e.key === 'currentMaterialId') {
    // 清除当前所有状态
    questions.value = [];
    selectedAnswers.value = {};
    showAnswers.value = false;
    currentIndex.value = 0;
    showAnswerCard.value = false;
    
    // 重新加载题目
    if (e.newValue) {
      await loadQuestions();
    }
  }
};

// 加载题目的方法
const loadQuestions = async () => {
  const materialId = localStorage.getItem('currentMaterialId');
  if (materialId) {
    try {
      const response = await generateQuestion(materialId);
      if (response.status === 200 && response.data.data) {
        // 处理返回的题目数据
        questions.value = response.data.data.map(question => ({
          ...question,
          // 移除可能为null的时间字段
          createTime: undefined,
          updateTime: undefined
        }));
      }
    } catch (error) {
      console.error('获取题目失败:', error);
    }
  }
};
const currentIndex = ref(0);
const selectedAnswers = ref({});
const showAnswers = ref(false);

const currentQuestion = computed(() => questions.value[currentIndex.value]);

const getDifficultyText = (level) => {
  const levels = ['简单', '中等', '困难'];
  return levels[level - 1] || '未知';
};

const selectAnswer = (questionId, option) => {
  if (!showAnswers.value) {
    selectedAnswers.value[questionId] = option;
  }
};

const nextQuestion = () => {
  if (currentIndex.value < questions.value.length - 1) {
    currentIndex.value++;
  }
};

const prevQuestion = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--;
  }
};

const submitAllAnswers = async () => {
  const materialId = localStorage.getItem('currentMaterialId');
  if (!materialId) {
    console.error('未找到材料ID');
    return;
  }

  try {
    const response = await submitAnswers(selectedAnswers.value, materialId);
    if (response.status === 200) {
      showAnswers.value = true;
      // 可以添加提交成功的提示
    }
  } catch (error) {
    console.error('提交答案失败:', error);
    // 可以添加提交失败的提示
  }
};

const resetAnswers = () => {
  selectedAnswers.value = {};
  showAnswers.value = false;
  currentIndex.value = 0;
};
const showAnswerCard = ref(false);

const toggleAnswerCard = () => {
  showAnswerCard.value = !showAnswerCard.value;
};

const goToQuestion = (index) => {
  currentIndex.value = index;
  showAnswerCard.value = false;
};
</script>

<style scoped>
.question-display {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.questions-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.question-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.question-number {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.difficulty {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 14px;
}

.level-1 {
  background: #e8f5e9;
  color: #2e7d32;
}

.level-2 {
  background: #fff3e0;
  color: #ef6c00;
}

.level-3 {
  background: #ffebee;
  color: #c62828;
}

.question-content {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 20px;
}

.options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option {
  display: flex;
  align-items: flex-start;
  padding: 12px 16px;
  border: 2px solid #eee;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.option:hover:not(.correct):not(.wrong) {
  border-color: #007aff;
  background: rgba(0, 122, 255, 0.05);
}

.option.selected {
  border-color: #007aff;
  background: rgba(0, 122, 255, 0.1);
}

.option.correct {
  border-color: #4caf50;
  background: rgba(76, 175, 80, 0.1);
}

.option.wrong {
  border-color: #f44336;
  background: rgba(244, 67, 54, 0.1);
}

.option-label {
  font-weight: 600;
  margin-right: 12px;
  color: #666;
}

.option-content {
  flex: 1;
}

.explanation {
  margin-top: 20px;
  padding: 16px;
  background: #f5f5f5;
  border-radius: 8px;
}

.explanation-title {
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.explanation-content {
  color: #666;
  line-height: 1.6;
}

.actions {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.submit-btn, .reset-btn {
  padding: 12px 32px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  border: none;
  transition: all 0.2s;
}

.submit-btn {
  background: #007aff;
  color: white;
}

.submit-btn:hover {
  background: #0056b3;
}

.reset-btn {
  background: #f5f5f5;
  color: #666;
}

.reset-btn:hover {
  background: #e0e0e0;
}

.empty-state {
  text-align: center;
  padding: 48px;
  color: #666;
}

.question-navigation {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 12px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.nav-btn {
  padding: 8px 16px;
  border: 1px solid #007aff;
  border-radius: 6px;
  background: white;
  color: #007aff;
  cursor: pointer;
  transition: all 0.2s;
}

.nav-btn:hover:not(:disabled) {
  background: #007aff;
  color: white;
}

.nav-btn:disabled {
  border-color: #ccc;
  color: #ccc;
  cursor: not-allowed;
}

.question-progress {
  font-size: 16px;
  font-weight: 500;
  color: #666;
}

.submit-all-btn {
  padding: 8px 20px;
  background: #007aff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.2s;
}

.submit-all-btn:hover {
  background: #0056b3;
}
.answer-card-wrapper {
  position: relative;
  margin: 0 12px;
}

.answer-card-panel {
  position: absolute;
  top: calc(100% + 8px);
  left: 50%;
  transform: translateX(-50%);
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 16px;
  z-index: 1000;
  min-width: 280px;
}

.answer-card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  text-align: center;
}

.answer-card-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
}

.answer-card-item {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  transition: all 0.2s;
}

.answer-card-item:hover {
  border-color: #007aff;
  color: #007aff;
}

.answer-card-item.answered {
  background: #007aff;
  color: white;
  border-color: #007aff;
}

.answer-card-item.current {
  border-color: #007aff;
  color: #007aff;
  font-weight: bold;
}

.answer-card-item.answered.current {
  background: #0056b3;
  border-color: #0056b3;
  color: white;
}
</style>